package arrAndstr;

import java.util.Stack;

/*
    150. 逆波兰表达式求值
 */
public class T150 {

    public static void main(String[] args) {
        String[] tokens = new String[]{
                "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"
        };
        System.out.println(evalRPN(tokens));
    }

    public static int evalRPN(String[] tokens) {
        if (tokens.length == 1) return Integer.parseInt(tokens[0]);

        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            switch (token) {
                case "+": {
                    stack.push(stack.pop() + stack.pop());
                    break;
                }
                case "-": {
                    int v1 = stack.pop();
                    int v2 = stack.pop();
                    stack.push(v2 - v1);
                    break;
                }
                case "*": {
                    stack.push(stack.pop() * stack.pop());
                    break;
                }
                case "/": {
                    int v1 = stack.pop();
                    int v2 = stack.pop();
                    stack.push(v2 / v1);
                    break;
                }
                default: stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }
}
